package client.view;

import client.comms.PostData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: sam
 * Date: 07/04/12
 * Time: 16:00
 * To change this template use File | Settings | File Templates.
 */
public class SettingsPanel extends JPanel implements ActionListener, MouseListener{

    JFileChooser downloadDirOption;
    JTextField userPasswordText;
    JPasswordField passwordField;
    JTextField emailNotificationField;

    JTextField downloadDirText;
    JCheckBox uploadSetting;
    JCheckBox compressSetting;
    JCheckBox openDirSetting;
    JCheckBox emailSetting;

    boolean emailUser = false;
    boolean openDirOnDownload = false;
    boolean clearDoneUploads = false;
    boolean decompressDownload = false;

    public static String USER_SETTING_DOWNLOAD_DIR = "../";
    public static String USER_SETTING_EMAIL_NOTIFY = "yes";
    public static String USER_SETTING_AUTO_OPEN = "no";
    public static String USER_SETTING_CLEAR_UPLOADS = "no";
    public static String USER_SETTING_DECOMPRESS = "yes";

    public SettingsPanel() {

        downloadDirOption = new JFileChooser();
        downloadDirOption.setDialogType(JFileChooser.APPROVE_OPTION);
        downloadDirOption.setMultiSelectionEnabled(false);
        downloadDirOption.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        Border bevelBorder = BorderFactory.createBevelBorder(BevelBorder.LOWERED);

        JPanel contentPanel = new JPanel();

        JScrollPane scrollPane = new JScrollPane(contentPanel);
        scrollPane.setPreferredSize(new Dimension(590,305));

        Dimension settingsGap = new Dimension(590,10);

        Color labelColor = new Color(51,0,153);

        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        //contentPanel.setAlignmentX(Component.CENTER_ALIGNMENT);

        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        contentPanel.add(Box.createRigidArea(settingsGap));
        URL resourceURL;
        JLabel downloadLabel1 = new JLabel("Download Location");
        JLabel downloadLabel2 = new JLabel("Choose folder to store downloads");
        //resourceURL = getClass().getClassLoader().getResource(MFWindow.MEDIA+"tag_icon.png");
        //downloadLabel.setIcon(new ImageIcon(resourceURL));
        downloadLabel1.setForeground(labelColor);
        //downloadLabel2.setForeground(labelColor);
        downloadLabel1.setFont(new Font(downloadLabel1.getFont().getName(),Font.BOLD,downloadLabel1.getFont().getSize()+1));
        //downloadLabel2.setFont(new Font(downloadLabel1.getFont().getName(),Font.BOLD,downloadLabel1.getFont().getSize()+1));
        downloadLabel1.setAlignmentX(Component.CENTER_ALIGNMENT);
        downloadLabel2.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add(downloadLabel1);
        contentPanel.add(downloadLabel2);

        JPanel downloadOptPanel = new JPanel();
        JButton downloadDirBtn = new JButton("Browse");
        downloadDirBtn.addActionListener(this);
        // >>>>>>>>>>>>>>>>>>>>
        downloadDirText = new JTextField(USER_SETTING_DOWNLOAD_DIR);


        downloadDirText.setPreferredSize(new Dimension(200,25));
        downloadOptPanel.add(downloadDirBtn);
        downloadOptPanel.add(downloadDirText);
        contentPanel.add(downloadOptPanel);

        contentPanel.add(Box.createRigidArea(settingsGap));
        contentPanel.add(new JSeparator(JSeparator.HORIZONTAL));
        contentPanel.add(Box.createRigidArea(settingsGap));

        JLabel emailLabel = new JLabel("Upload Notification");
        //resourceURL = getClass().getClassLoader().getResource(MFWindow.MEDIA+"tag_icon.png");
        //emailLabel.setIcon(new ImageIcon(resourceURL));
        emailLabel.setForeground(labelColor);
        emailLabel.setFont(new Font(emailLabel.getFont().getName(),Font.BOLD,emailLabel.getFont().getSize()+1));
        emailLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add(emailLabel);

        JPanel emailOptPanel = new JPanel();
        // >>>>>>>>>>>>>>>>>>>>>>
        emailSetting = new JCheckBox("Email me when new tracks or genres are added");
        emailSetting.setName("emailSettingPref");
        emailSetting.addActionListener(this);
        emailOptPanel.add(emailSetting);
        contentPanel.add(emailOptPanel);

        contentPanel.add(Box.createRigidArea(settingsGap));
        contentPanel.add(new JSeparator(JSeparator.HORIZONTAL));
        contentPanel.add(Box.createRigidArea(settingsGap));


        JLabel openDirLabel1 = new JLabel("Downloads Folder");
        //resourceURL = getClass().getClassLoader().getResource(MFWindow.MEDIA+"tag_icon.png");
        //openDirLabel1.setIcon(new ImageIcon(resourceURL));
        openDirLabel1.setForeground(labelColor);
        openDirLabel1.setFont(new Font(openDirLabel1.getFont().getName(),Font.BOLD,openDirLabel1.getFont().getSize()+1));
        JLabel openDirLabel2 = new JLabel("(May not be supported on all systems)");

        openDirLabel1.setAlignmentX(Component.CENTER_ALIGNMENT);
        openDirLabel2.setAlignmentX(Component.CENTER_ALIGNMENT);

        contentPanel.add(openDirLabel1);

        JPanel openDirOptPanel = new JPanel();
        openDirOptPanel.setLayout(new BoxLayout(openDirOptPanel, BoxLayout.Y_AXIS));
        openDirSetting = new JCheckBox("Automatically open download folder on complete");
        openDirSetting.addActionListener(this);
        openDirSetting.setAlignmentX(Component.CENTER_ALIGNMENT);
        openDirOptPanel.add(openDirSetting);
        openDirOptPanel.add(openDirLabel2);
        contentPanel.add(openDirOptPanel);

        contentPanel.add(Box.createRigidArea(settingsGap));
        contentPanel.add(new JSeparator(JSeparator.HORIZONTAL));
        contentPanel.add(Box.createRigidArea(settingsGap));

        JLabel clearUploadLabel = new JLabel("Upload List");
        //resourceURL = getClass().getClassLoader().getResource(MFWindow.MEDIA+"tag_icon.png");
        //clearUploadLabel.setIcon(new ImageIcon(resourceURL));
        clearUploadLabel.setForeground(labelColor);
        clearUploadLabel.setFont(new Font(clearUploadLabel.getFont().getName(),Font.BOLD,clearUploadLabel.getFont().getSize()+1));
        clearUploadLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add(clearUploadLabel);

        JPanel uploadOptPanel = new JPanel();
        uploadSetting = new JCheckBox("Clear upload list when upload complete");
        uploadSetting.addActionListener(this);
        uploadOptPanel.add(uploadSetting);
        contentPanel.add(uploadOptPanel);

        contentPanel.add(Box.createRigidArea(settingsGap));
        contentPanel.add(new JSeparator(JSeparator.HORIZONTAL));
        contentPanel.add(Box.createRigidArea(settingsGap));

        JLabel compressLabel = new JLabel("Decompress / Extract");
        compressLabel.setForeground(labelColor);
        compressLabel.setFont(new Font(compressLabel.getFont().getName(),Font.BOLD,compressLabel.getFont().getSize()+1));
        compressLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add(compressLabel);

        JPanel compressOptPanel = new JPanel();
        compressSetting = new JCheckBox("Keep download compressed");
        compressSetting.addActionListener(this);
        compressOptPanel.add(compressSetting);
        contentPanel.add(compressOptPanel);

        contentPanel.add(Box.createRigidArea(settingsGap));
        contentPanel.add(new JSeparator(JSeparator.HORIZONTAL));
        contentPanel.add(Box.createRigidArea(settingsGap));

        JLabel passwordLabel = new JLabel("Change Password");
        passwordLabel.setForeground(labelColor);
        passwordLabel.setFont(new Font(compressLabel.getFont().getName(),Font.BOLD,compressLabel.getFont().getSize()+1));
        passwordLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add(passwordLabel);

        JPanel passwordOptPanel = new JPanel();
        //userPasswordText = new JTextField("");
        passwordField = new JPasswordField(20);
        passwordField.setBorder(bevelBorder);
        passwordField.addActionListener(this);
        //passwordField.setActionCommand(OK);
        //userPasswordText.setPreferredSize(new Dimension(200,25));
        passwordOptPanel.add(passwordField);
        contentPanel.add(passwordOptPanel);


        contentPanel.add(Box.createRigidArea(settingsGap));
        contentPanel.add(new JSeparator(JSeparator.HORIZONTAL));
        contentPanel.add(Box.createRigidArea(settingsGap));

        JLabel emailNotificationLabel = new JLabel("Change Email");
        emailNotificationLabel.setForeground(labelColor);
        emailNotificationLabel.setFont(new Font(compressLabel.getFont().getName(),Font.BOLD,compressLabel.getFont().getSize()+1));
        emailNotificationLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add(emailNotificationLabel);

        JLabel emailNotificationLabel2 = new JLabel("Change where notification of new uploads get sent");
        emailNotificationLabel2.setAlignmentX(Component.CENTER_ALIGNMENT);
        contentPanel.add(emailNotificationLabel2);

        JPanel emailNotificationOptPanel = new JPanel();
        //userPasswordText = new JTextField("");
        emailNotificationField = new JTextField(25);
        emailNotificationField.setBorder(bevelBorder);
        //passwordField.addActionListener(this);
        //passwordField.setActionCommand(OK);
        //userPasswordText.setPreferredSize(new Dimension(200,25));
        emailNotificationOptPanel.add(emailNotificationField);
        contentPanel.add(emailNotificationOptPanel);

        contentPanel.add(Box.createRigidArea(settingsGap));
        contentPanel.add(new JSeparator(JSeparator.HORIZONTAL));
        contentPanel.add(Box.createRigidArea(settingsGap));


        JPanel savePanel = new JPanel();
        JButton saveBtn = new JButton("Save");
        resourceURL = getClass().getClassLoader().getResource(MFWindow.MEDIA+"flag_icon.png");
        Icon tmpIcon = new ImageIcon(resourceURL);
        saveBtn.setIcon(tmpIcon);
        saveBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
        savePanel.add(saveBtn);
        contentPanel.add(savePanel);

        saveBtn.addActionListener(this);
        contentPanel.add(Box.createRigidArea(settingsGap));
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        //contentPanel.add(Box.createRigidArea(new Dimension(590,100)));
        //contentPanel.add(new JSeparator(JSeparator.HORIZONTAL));
        //contentPanel.add(Box.createRigidArea(new Dimension(590,20)));

        //add(contentPanel);

        //JPanel mainPanel = new JPanel();

        /*mainPanel.setBorder(BorderFactory.createEmptyBorder(
                                5, //top
                                5,     //left
                                20, //bottom
                                20));   //right  */


        //mainPanel.add(scrollPane, BorderLayout.CENTER);

        add(scrollPane, BorderLayout.CENTER);
    }

    public void init() {

    }

    public void actionPerformed(ActionEvent actionEvent) {

        String strAction = actionEvent.getActionCommand();
        Object eventSrc = actionEvent.getSource();

        ReportsPanel.log("actionPerformed "+strAction);

        if(strAction.equals("Save")) {
            saveSettings();
        } else if(strAction.equals("Select Download Folder")) {
            int returnValue = downloadDirOption.showOpenDialog(null);
        }else if(strAction.equals("Email me when new tracks or genres are added")) {
            emailUser = !emailUser;
        }else if(strAction.equals("Automatically open download folder on complete")) {
            openDirOnDownload = !openDirOnDownload;
        }else if(strAction.equals("Clear upload list when upload complete")){
            clearDoneUploads = !clearDoneUploads;
        }else if(strAction.equals("Keep download compressed")) {
            decompressDownload = !decompressDownload;
        }else if(eventSrc.equals(passwordField)) {
            //JOptionPane optionPane = new JOptionPane("Are you sure you want to save current settings?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
            //JDialog dialog = optionPane.createDialog(null, "Manual Creation");
            //dialog.setVisible(true);

            int confirm = JOptionPane.showOptionDialog(this, "Are you sure you want to save current settings?", "Exit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.YES_NO_OPTION,null,null,null);

            // yes = 0, no = 1

            if(confirm == 0 ) {
                saveSettings();
            }
        } else if(strAction.equals("Browse")) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            int returnValue = fileChooser.showOpenDialog(null);
            File file = fileChooser.getSelectedFile();
            downloadDirText.setText(file.getAbsolutePath());
            ReportsPanel.log("Download Dir "+ file.getAbsolutePath());
        }
    }

    public void saveSettings() {

        ReportsPanel.log("SettingsPanel.saveSettings()");

        USER_SETTING_DOWNLOAD_DIR = downloadDirText.getText();
        USER_SETTING_EMAIL_NOTIFY = emailUser ? "yes" : "no";
        USER_SETTING_AUTO_OPEN = openDirOnDownload ? "yes" : "no";
        USER_SETTING_CLEAR_UPLOADS = clearDoneUploads  ? "yes" : "no";
        USER_SETTING_DECOMPRESS = decompressDownload  ? "yes" : "no";

        // TODO escape slashes USER_SETTING_DOWNLOAD_DIR, e.g. Windows user C:\ in DB?

        /**
         * As to your actual problem: the \ is an escape character in both the String and in regex. You need to re-escape it as well:
            But you don't necessarily need regex for this, simply because you want an exact character-by-character replace and you don't need patterns here.
            So String#replace() would suffice:
         */

        if(USER_SETTING_DOWNLOAD_DIR.indexOf("\\") > -1) {
            USER_SETTING_DOWNLOAD_DIR.replace("\\", "\\\\");

        }

        String userPassword = String.valueOf(passwordField.getPassword());
        String userNotificationAddress = String.valueOf(emailNotificationField.getText());

        ReportsPanel.log("USER_SETTING_DOWNLOAD_DIR "+USER_SETTING_DOWNLOAD_DIR);
        ReportsPanel.log("USER_SETTING_EMAIL_NOTIFY "+USER_SETTING_EMAIL_NOTIFY);
        ReportsPanel.log("USER_SETTING_AUTO_OPEN "+USER_SETTING_AUTO_OPEN);
        ReportsPanel.log("USER_SETTING_CLEAR_UPLOADS "+USER_SETTING_CLEAR_UPLOADS);
        ReportsPanel.log("USER_SETTING_DECOMPRESS "+USER_SETTING_DECOMPRESS);

        /**
         * <?xml version="1.0" encoding="ISO-8859-1"?>
            <MFRequest>
            <Request type='SaveSettings' data=''/>
            <UserPrefs download_pref='../' email_pref='yes' open_on_download_pref='no' clear_uploads_pref='no' decompress_pref='no' password_pref='no'/>
            </MFRequest>
         */

        StringBuilder strReq = new StringBuilder();

        strReq.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"+"\n");
        strReq.append("<MFRequest>"+"\n");
        strReq.append("<Request type='SaveSettings' data=''/>"+"\n");

        strReq.append("<UserPrefs download_pref='"+USER_SETTING_DOWNLOAD_DIR+
                "' email_pref='"+USER_SETTING_EMAIL_NOTIFY+
                "' open_on_download_pref='"+USER_SETTING_AUTO_OPEN+
                "' clear_uploads_pref='"+USER_SETTING_CLEAR_UPLOADS+
                "' decompress_pref='"+USER_SETTING_DECOMPRESS+
                "' password_pref='"+userPassword+
                "' notification_address_pref='"+userNotificationAddress+"'/>"+"\n");

        strReq.append("</MFRequest>"+"\n");

        ReportsPanel.log(strReq.toString());

        PostData postData = new PostData();
        Document settingsResponse = postData.sendDataForWriteReponse(strReq.toString());

        NodeList nList = settingsResponse.getElementsByTagName("Response");
        Node nNode = nList.item(0);
        Element eElement = (Element) nNode;
        String type = eElement.getAttribute("type");

        if(type.equals("Error")) {
            String errorCode = eElement.getAttribute("code");

            if(errorCode.equals("MF_SESSION_EXPIRED")) {
                JOptionPane.showMessageDialog(this,"Saving Failed. Session has expired. Please login.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } else if(type.equals("SaveSettings")) {

            JOptionPane.showMessageDialog(this,"Settings updated.", "Info", JOptionPane.INFORMATION_MESSAGE);

        }
    }

    public void updateUserPreferences() {

        // USER_SETTING_DOWNLOAD_DIR already set, non boolean

        emailUser = USER_SETTING_EMAIL_NOTIFY.equals("yes");
        openDirOnDownload = USER_SETTING_AUTO_OPEN.equals("yes");
        clearDoneUploads = USER_SETTING_CLEAR_UPLOADS.equals("yes");
        decompressDownload = USER_SETTING_DECOMPRESS.equals("yes");

        downloadDirText.setText(SettingsPanel.USER_SETTING_DOWNLOAD_DIR);
        uploadSetting.setSelected(clearDoneUploads);
        compressSetting.setSelected(decompressDownload);
        openDirSetting.setSelected(openDirOnDownload);
        emailSetting.setSelected(emailUser);
    }

    public void mouseClicked(MouseEvent mouseEvent) {
    }

    public void mousePressed(MouseEvent mouseEvent) {
    }

    public void mouseReleased(MouseEvent mouseEvent) {
    }

    public void mouseEntered(MouseEvent mouseEvent) {
    }

    public void mouseExited(MouseEvent mouseEvent) {
    }
}
